from django.shortcuts import render

# Create your views here.
import random
from django import http
from django.views import View
from shicifang.settings import logger
from django_redis import get_redis_connection
# from apps.verifications.libs.yuntongxun.ccp_sms import CCP



# 短信验证码
class SMSCodeView(View):
    def get(self, requset, mobile):
        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')

        # 后端 避免 发送短信过于频繁
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return http.JsonResponse({'code': 400, 'errmsg': '发送短信过于频繁'})
        # 生成验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)


        # 保存验证码
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)

        # 发送验证码
        # CCP().send_template_sms(mobile,[sms_code, 5], 1)
        print('短信验证码:',sms_code)
        # redis_conn = get_redis_connection('verify_code')
        # sms_code_server = redis_conn.get('sms_%s' % mobile)
        # print(sms_code_server.decode())
        # # 1. 创建redis pipeline
        # pl = redis_conn.pipeline()
        # # 2.将任务交给管道
        # # 设置 发送短信过于频繁 标识
        # pl.setex('send_flag_%s' % mobile, 60, 1)
        # # 3.2 存储redis数据库 mobile:6位码
        # pl.setex('sms_%s' % mobile, 300, sms_code)
        #
        # pl.execute()

        # # - 4.celery--异步调用 --使用第三方 容联云 发短信
        # from celery_tasks.sms.tasks import ccp_send_sms_code
        # ccp_send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({'code': 0, 'errmsg': '发送短信成功!'})
